﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using OA.Core.DataAccessHelper;
using OA.Core.Helper;
using OA.Model;
using OA.Model.DB;
using OA.Model.Mapper;
using OA.Model.Result;
using OA.Web.Code;
using OA.Web.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Z.EntityFramework.Extensions.EFCore;
using Z.EntityFramework.Plus;
using OA.Model.View;
using OA.Core.Security;
using OA.BLL;
using OA.Core.Oss;

namespace OA.Web.Controllers
{
    public class HomeController : BaseController
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ICookie _cookie;
        private readonly IMemoryCache _cache;

        public HomeController(ILogger<HomeController> logger, IHttpContextAccessor httpContextAccessor, ICookie cookie, IMemoryCache cache) :base(httpContextAccessor, cookie, cache)
        {
            _logger = logger;
            _httpContextAccessor = httpContextAccessor;
            _cookie = cookie;
            _cache = cache;
        }

        public IActionResult Index()
        {
            return View();
        }


        public IActionResult InintPwd()
        {
            using (var dbContext = new MyDbContext())
            {
                var list=dbContext.Employee.ToList();
                foreach (var item in list)
                {
                    string password = (item.EmpID.ToLower() + "123456").ToMd5String();
                    dbContext.Employee.Where(m => m.ID == item.ID).Update(m => new Employee() { Password = password });
                }
                dbContext.SaveChanges();
            }
            return View();
        }


        [HttpPost]
        public IActionResult Index(string userName, string password, string validateCode, string url)
        {
            if (string.IsNullOrWhiteSpace(userName))
            {
                return Json(new { code = "-1", msg = "请输入账号" });
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                return Json(new { code = "-1", msg = "请输入密码" });
            }
            if (string.IsNullOrWhiteSpace(validateCode))
            {
                return Json(new { code = "-1", msg = "请输入验证码" });
            }

            if (HttpContext.Session.GetString("CaptchaResult_0") != validateCode.ToLower())
            {
                HttpContext.Session.Remove("CaptchaResult_0");
                return Json(new { code = "-1", msg = "验证码输入错误" });
            }

            LoginLog infoLoginLog = new LoginLog();
            infoLoginLog.IP = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
            infoLoginLog.UserName = userName;
            infoLoginLog.CreateDateTime = DateTime.Now;

            try
            {
                using (var dbContext = new MyDbContext())
                {
                    var infoEmployee = dbContext.Employee.Where(m => m.EmpID == userName).FirstOrDefault();
                    if(infoEmployee==null)
                    {
                        return Json(new { code = "-1", msg = "用户名或密码输入错误" });
                    }
                    if (infoEmployee.Status == 0)
                    {
                        return Json(new { code = "-1", msg = "账号被禁用！" });
                    }
                    else if (infoEmployee.Status == 2)
                    {
                        return Json(new { code = "-1", msg = "账号异常！请联系管理员解除账号异常状态" });
                    }
                    else if (infoEmployee.LockTime != null)
                    {
                        TimeSpan ts = DateTime.Now - (DateTime)infoEmployee.LockTime;
                        if (ts.TotalMinutes < 15)
                        {
                            return Json(new { code = "-1", msg = $"当前账号已被锁定。离解锁时间还有{(int)(15 - ts.TotalMinutes)}分钟" });
                        }
                    }
                    string mm = (userName.ToLower() + password).ToMd5String();
                    if (infoEmployee == null || infoEmployee.Password != mm)
                    {
                        infoLoginLog.Status = -1;
                        dbContext.LoginLog.Add(infoLoginLog);
                        if (infoEmployee.ErrorTimes > 10)
                        {
                            dbContext.Employee.Where(m => m.EmpID == userName).Update(m => new Employee() { LockTime = DateTime.Now, ErrorTimes = infoEmployee.ErrorTimes + 1 });
                        }
                        else
                        {
                            dbContext.Employee.Where(m => m.EmpID == userName).Update(m => new Employee() { ErrorTimes = infoEmployee.ErrorTimes + 1 });
                        }
                        dbContext.SaveChanges();
                        return Json(new { code = "-1", msg = "用户名或密码输入错误" });
                    }
                    else
                    {
                        infoLoginLog.Status = 1;
                        dbContext.LoginLog.Add(infoLoginLog);
                        dbContext.Employee.Where(m => m.EmpID == userName).Update(m => new Employee() { ErrorTimes = 0 });
                        dbContext.SaveChanges();
                        _cookie.SetCookies(CookieHelper.UserID, infoEmployee.EmpID.ToBase62());
                        if (string.IsNullOrWhiteSpace(infoEmployee.Pic)) { infoEmployee.Pic = "/images/default_emp.png"; }
                        _cookie.SetCookies(CookieHelper.Avatar_User, infoEmployee.Pic);
                        return Json(new { code = 1 });
                    }
                }
            }
            catch (Exception ex)
            {
                return Json(new { code = "-1", msg = "系统繁忙！请稍后重试" });
            }
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        public IActionResult ValidateImage(string type)
        {
            CaptchaResult captchaResult = new CaptchaResult();
            Tuple<string, int> code = CaptchaHelper.GetCaptchaCode();
            captchaResult.Data = CaptchaHelper.CreateCaptchaImage(code.Item1.ToString());
            HttpContext.Session.SetString("CaptchaResult_" + type, code.Item2.ToString());
            return Json(captchaResult);
        }

        /// <summary>
        /// 如果文件上传成功，OSS会根据用户请求中的callback参数和callback-var自定义参数，将特定内容以POST方式发送给应用服务器。
        /// </summary>
        /// <param name="bucket"></param>
        /// <param name="url"></param>
        /// <param name="size"></param>
        /// <param name="mimeType"></param>
        /// <param name="my_var"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult OssCallBack(string bucket, string url, string my_var)
        {
             
            string[] textArray1 = new string[] { "https://", bucket, ".", my_var, "/", url };
            string str = string.Concat(textArray1);
            List<string> list = new List<string> { str };
            var result = new
            {
                errno = 0,
                data = list
            };
            return Json(result);
        }

        [HttpGet]
        public IActionResult GetOssSignature(string signature)
        {
            PolicyInfoResult policyInfoResult = new PolicyInfoResult();
            string userID = signature.FromBase62<string>();
            if (string.IsNullOrWhiteSpace(userID))
            {
                policyInfoResult.State = 400;
                policyInfoResult.Msg = "非法的上传";
            }
            else {
                CacheHelper cacheHelper = new CacheHelper(_cache);
                OssConfig config = cacheHelper.GetConfig<OssConfig>();
                policyInfoResult = JsonHelper.DeserializeObj<PolicyInfoResult>(JsonHelper.SerializeObject(OssHelper.GetPolicyInfo(config, userID)));
                policyInfoResult.Url = config.Endpoint;
            }
            return Json(policyInfoResult);
        }
    }
}
